package dao;
import model.Article;
import util.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ArticleDao {
    /**
     * 插入新文章
     */
    public boolean insert(String title, String content, int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "INSERT INTO articles (title, content_markdown, user_id, created_at, status) VALUES (?, ?, ?, NOW(), 1)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, title);
            stmt.setString(2, content);
            stmt.setInt(3, userId);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt, null);
        }
    }

    /**
     * 获取所有文章
     */
    public List<Article> getAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<Article> articles = new ArrayList<>();
    
        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT a.*, u.username as author_name " +
                    "FROM articles a " +
                    "JOIN users u ON a.user_id = u.id " +
                    "WHERE a.status = 1 " +
                    "ORDER BY a.created_at DESC";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
    
            while (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setContentMarkdown(rs.getString("content_markdown"));
                article.setAuthorName(rs.getString("author_name"));
                article.setUserId(rs.getInt("user_id")); // 添加这一行，设置userId
                article.setViewCount(rs.getInt("view_count"));
                article.setCreatedAt(rs.getTimestamp("created_at"));
                articles.add(article);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
        return articles;
    }

    /**
     * 根据id获取文章详情
     */
    public Article getById(int id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
    
        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT a.*, u.username as author_name " +
                    "FROM articles a " +
                    "JOIN users u ON a.user_id = u.id " +
                    "WHERE a.id = ? AND a.status = 1";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            rs = stmt.executeQuery();
    
            if (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setContentMarkdown(rs.getString("content_markdown"));
                article.setAuthorName(rs.getString("author_name"));
                article.setUserId(rs.getInt("user_id")); // 添加这一行，设置userId
                article.setViewCount(rs.getInt("view_count"));
                article.setCreatedAt(rs.getTimestamp("created_at"));
                return article;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
        return null;
    }
    
    /**
     * 根据ID删除文章（软删除）
     */
    public boolean deleteById(int articleId) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "UPDATE articles SET status = 0 WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, articleId);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt, null);
        }
    }
    
    /**
     * 检查文章是否属于指定用户
     */
    public boolean isArticleOwnedByUser(int articleId, int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT COUNT(*) FROM articles WHERE id = ? AND user_id = ? AND status = 1";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, articleId);
            stmt.setInt(2, userId);
            rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }
}